Customization and Maps


Table of Contents¶

  • 1. Customizing Plots
  • 2. Faceting and Themes
  • 3. Maps with leaflet

  • Estimated Time Needed: 45 min

    Introduction

    In this notebook you will learn how to customize your plots, add themes, and change the color palette. Additionally, you will learn more about creating maps with the "leaflet" package.

    1. Customizing Plots
    ¶

    In this section of customizing plots, you will learn how to customize titles and labels, text labels, and add line and text annotations to plots.

    Before jumping into knowledge, let's install the necessary packages.

    In [1]:
    install.packages(c("rlang","fastmap"))
    install.packages("https://cran.r-project.org/src/contrib/htmltools_0.5.6.tar.gz",repos=NULL)
    install.packages("https://cran.r-project.org/src/contrib/htmlwidgets_1.6.2.tar.gz",repos=NULL)
    
    Updating HTML index of packages in '.Library'
    Making 'packages.html' ... done
    Warning message in download.file(p, destfile, method, mode = "wb", ...):
    “cannot open URL 'https://cran.r-project.org/src/contrib/htmltools_0.5.6.tar.gz': HTTP status was '404 Not Found'”
    Error in download.file(p, destfile, method, mode = "wb", ...) : 
      cannot open URL 'https://cran.r-project.org/src/contrib/htmltools_0.5.6.tar.gz'
    
    Warning message in download.file(p, destfile, method, mode = "wb", ...):
    “cannot open URL 'https://cran.r-project.org/src/contrib/htmlwidgets_1.6.2.tar.gz': HTTP status was '404 Not Found'”
    Error in download.file(p, destfile, method, mode = "wb", ...) : 
      cannot open URL 'https://cran.r-project.org/src/contrib/htmlwidgets_1.6.2.tar.gz'
    

    Please note that 'rlang', 'fastmap', htmltools', 'htmlwidgets' are some of dependent packages required to work with "leaflet" package.

    Restart R Kernel and then load 'ggplot2' and 'htmltools' packages.

    In [2]:
    library(ggplot2)
    library(htmltools)
    

    Labels¶

    It is important to add labels and titles to your plots. Often, default labels are lacking in descriptive information, so it is better to customize the labels yourself so they convey the intended meaning to those who will consume your data visualizations.

    You can use the labs() function to change the x axis label, y axis label, the legend title, the entire plot title, the plot subtitle, and the plot captions. You do not have to add all these labels, but it is a good idea to make sure that at least the x and y axis, and the title are informative.

    Here is the labs() documentation:

    labs(
      x = ...,        # x axis label
      y = ...,        # y axis label
      color = ...,    # legend title
      title = ,       # plot title
      subtitle = ..., # plot subtitle
      caption = ...   # plot caption
    )
    

    An alternative way to update the x axis, y axis, or title and subtitle labels is to use these functions:

    xlab(label)
    ylab(label)
    ggtitle(label, subtitle = ...)
    

    To find more details, please read the full labs() documentation.

    In this example, you are plotting the weight of cars against the mileage from the mtcars dataset. To people unfamiliar with this dataset, they may not understand what wt or mpg means.

    In [3]:
    ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point(aes(color = factor(cyl)))
    

    Instead, if you customize the labels and titles, this chart becomes much more informative.

    In [4]:
    ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point(aes(color = factor(cyl))) +
      labs(
        x = "Weight (1000 lbs)", 
        y = "Miles/(US) gallon", 
        color = "Cylinders",
        title = "Mileage by weight and cylinders",
        subtitle = "Source: 1974 Motor Trend US magazine"
    )
    

    Text labels¶

    Another helpful function to use in plots is geom_text(), which adds text labels to data points.

    This example again uses the mileage and weight of cars, except that we now want to display the name of the car that corresponds with each data point on the plot.

    In mtcars, the row name contains the name of the cars. You can use geom_text() with the rownames() function to label each point with the name of the car. So, in the aes() of geom_text(), set the label parameter equal to rownames(mtcars).

    In [5]:
    ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point(aes(color = factor(cyl))) +
      geom_text(aes(label = rownames(mtcars)))
    

    In the plot above, you can see that the car names appear, as expected, but it looks messy.

    To fix the plot:

    • You can remove the overlapping text by setting the check_overlap parameter of geom_text() to TRUE.
    • Also, setting the hjust parameter to “inward’ makes sure all the text is positioned within the plot.
    In [ ]:
    ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point(aes(color = factor(cyl))) +
      geom_text(aes(label = rownames(mtcars)),
                    check_overlap = TRUE, hjust = "inward")
    

    Now you can notice that although some points are removed, the overall visualization is better. You can more clearly see now that automatic cars have low mileage and greater weight while manual cars have better mileage and lighter weight.

    Annotations¶

    You can create custom annotations to emphasize important elements of your plot. For example, there may be an outlier on your scatter plot that you want to label or a spike in your line plot that you want to highlight. You can use custom annotations to emphasize these areas.

    There are several functions you can use to create custom annotations.

    • geom_vline() creates vertical lines
    • geom_hline() creates horizonal lines
    • geom_abline() creates lines that have a slope and intercept
    • geom_rect() creates rectangles

    You can also use the annotate() function, which provides even more customization. You pass in a “geom”, such as “point” or “text”, and then draw these customized elements on the plot. For example:

    annotate(geom = "line")   # geom_line()
    annotate(geom = "text")   # geom_text()
    

    Using this is an alternative to functions like geom_text() and geom_label() can shorten the code length.

    Now, let's use annotations in an example. Consider this histogram of the miles per gallon variable.

    In [6]:
    ggplot(mtcars, aes(x = mpg)) + 
      geom_histogram(bins = 10)
    

    Let's add a line to show the median and label it. First, find the median

    In [7]:
    # Find the median value of miles per gallon
    median(mtcars$mpg)
    
    19.2

    To add a vertical line to show the median, use the geom_vline() function.

    Next, annotate the line using annotate(). To add the text, set geom to ”text” and set label to the desired text. Set x and y to position where the text will go. And finally, set hjust (or horizonal justification) to 0, which makes the text completely left justified at the x position.

    In [8]:
    ggplot(mtcars, aes(x = mpg)) + 
      geom_histogram(bins = 10) + 
      labs(x = "Miles/(US) gallon", 
           y = "Count", 
           title = "Distribution of Miles/Gallon") +
      geom_vline(aes(xintercept = 19.2), 
                 color = "red") +
      annotate(geom = "text", 
               label = "Median = 19.2", 
               x = 21, 
               y = 7, 
               hjust = 0, 
               color = "red")
    

    A caveat of having custom annotations is that it often time requires a lot of manual trial and error in positioning the shapes and lines. So keep in mind that you may not want to customize everything to the point that you spend too much time trying to add a line or until your plot becomes too overwhelming. Just add enought to enhance your visualization to users.

    Question #1:

    Using the mtcars dataset, create a scatter plot of the gross horsepower on the x-axis and the 1/4 mile time on the y-axis. Add labels and a title to the plot. Also, add a line separating horsepowers greater than 200.

    As a bonus, add a text annotation next to the point that has the slowest 1/4 mile time value.

    In [9]:
    i_max <- which.max(mtcars$qsec)  # finds index of the max of mtcars$qsec
    
    ggplot(mtcars, aes(x = hp, y = qsec)) +
      geom_point() + 
      labs(x = "Gross horsepower", y = "1/4 mile time") +
      geom_vline(aes(xintercept = 200), 
                 color = "red") +
      annotate(geom = "text", 
               label = "slowest", 
               x = mtcars$hp[i_max] + 5,  # the hp value that corresponds to the max qsec value
               y = mtcars$qsec[i_max],    # could use max(mtcars$qsec) 
               hjust = 0,                 # left aligns text
               color = "red")
    
    Click here for the solution.
    i_max <- which.max(mtcars$qsec)  # finds index of the max of mtcars$qsec
    
    ggplot(mtcars, aes(x = hp, y = qsec)) +
      geom_point() + 
      labs(x = "Gross horsepower", y = "1/4 mile time") +
      geom_vline(aes(xintercept = 200), 
                 color = "red") +
      annotate(geom = "text", 
               label = "slowest", 
               x = mtcars$hp[i_max] + 5,  # the hp value that corresponds to the max qsec value
               y = mtcars$qsec[i_max],    # could use max(mtcars$qsec) 
               hjust = 0,                 # left aligns text
               color = "red")
    

    2. Faceting and Themes
    ¶

    Faceting¶

    Facets divide a plot into subplots based on the values of discrete or categorical variables. In ggplot, you can add the function facet_wrap(). You pass in tilde and the variable you are faceting. Using facets are a good way to explore the data further. With facetting, you can make multi-panel plots and control how the scales of one panel relate to the scales of another. For example, facets can help you to look at attributes for each type of car.

    Faceting example¶

    Let’s look at an example. Displayed here is the distribution of miles per gallon of all the cars in the mtcars dataset. Now, what if you want to break it up by the number of cylinders each car has?

    You can add facet_wrap() on the cyl variable, which contains the number of cylinders.

    In [ ]:
    ggplot(mtcars, aes(x = mpg)) + 
        geom_histogram() + 
        facet_wrap(.~cyl)
    

    Now you can see the distributions of miles per gallon for each number of cylinders. From this faceted histogram, you can see that cars with the least number of cylinders have a wider range of miles per gallon and cars with the most cylinders have the least miles per gallon.

    Using facet_wrap() makes creating these plots simple. If you used base R plotting, you would have to filter the data yourself and create a new plot for each number of cylinders. You can apply faceting to all the other plots you have learned about, like bar plots, box plots, scatter plots, and so on.

    Question #2 (a):

    Create a bar chart of number of cylinders and facet by transmission. Add labels and a title.

    In [10]:
    # Write your code below and press Shift+Enter to execute 
    # Write your code below and press Shift+Enter to execute 
    ggplot(mtcars, aes(x = factor(cyl))) + 
      geom_bar() + 
      facet_wrap(.~am) + 
      labs(x = "Number of cylinders", title = "Cylinders by transmission type (0 is automatic, 1 is manual)")
    
    Click here for the solution.
    ggplot(mtcars, aes(x = factor(cyl))) + 
      geom_bar() + 
      facet_wrap(.~am) + 
      labs(x = "Number of cylinders", title = "Cylinders by transmission type (0 is automatic, 1 is manual)")
    

    Themes¶

    You have seen how ggplot2 makes faceting simple by just adding one function. In line with this idea of making visualization simpler, you can change the themes of your plots simply by adding a different theme function. ggplot2 comes with eight built-in themes.

    • theme_gray() is the default option. Even if you do not add a theme function, your plot will have this theme
    • theme_bw() is a variation on theme_gray() that uses a white background and thin grey grid lines.
    • theme_minimal() has no background annotations.
    • theme_classic() has x and y axis lines but no grid lines.
    • theme_void() is a completely empty theme.
    • theme_linedraw() has only black lines of various widths on white backgrounds.
    • theme_light() is similar to theme_linedraw() but with light grey lines and axes.
    • theme_dark() is similar to theme_light(), with similar line sizes, but with a dark background.

    You can play around with different themes and see which one you like better.

    In [16]:
    ggplot(mtcars, aes(cyl)) + geom_bar() + theme_dark()
    

    Color Palettes¶

    Color palettes are a set of colors that the plot will use. In a previous lesson on pie charts, you learned a bit about changing color palettes. Color palettes change the color of the aesthetic color or fill. For example, common functions to use are:

    scale_colour_brewer()
    scale_fill_brewer()
    
    • For categorical or qualitative variables
      • Some example palettes are: Accent, Dark2, Paired, Set1
      • The colors used in these palettes should be distiguishable from each other to differentiate different categories
    • For numerical or sequential variables
      • Some example palettes are: Blues, BuGn, Greens, Greys
      • These palettes often go from light to dark colors

    You can check the documentation for more palette types.

    For example, say you want to represent each number of cylinder by a different color. To do this, set the fill to be cyl_factor, then use scale_fill_brewer() since you want to change the colors of the fill aesthetic. Additionally, cyl_factor is categorical variable, so you should use a palette better suited for that.

    In [12]:
    mtcars$cyl_factor = factor(mtcars$cyl)
    
    ggplot(mtcars, aes(x = cyl_factor, fill = cyl_factor)) + 
      geom_bar() + 
      scale_fill_brewer(palette = "Accent")
    

    Question #2 (b):

    Use mtcars to create a bar chart of the number of forward gears. Remember to set fill as gears. Chose a built in theme and a color palette different from the examples.

    In [17]:
    # Write your code below and press Shift+Enter to execute 
    
    # Write your code below and press Shift+Enter to execute 
    mtcars$gearfactor <- factor(mtcars$gear)
    
    
    ggplot(mtcars, aes(x = gear_factor, fill = gear_factor)) + 
      geom_bar() +  
      theme_minimal() + 
      scale_fill_brewer(palette = "Set3")
    
    Click here for the solution.
    # One example solution
    
    mtcars$gear_factor <- factor(mtcars$gear)
    
    ggplot(mtcars, aes(x = gear_factor, fill = gear_factor)) + 
      geom_bar() +  
      theme_minimal() + 
      scale_fill_brewer(palette = "Set3")
    

    Customizing themes¶

    In addition to built-in themes, you can customize your own. There are many different aspects of the plots that you can customize, like the axis, the legend, and the entire plot. To see all the options, look at the documentation with ? theme.

    theme(
      axis.line = ...,
      legend.background = ...,
      plot.title = ...,
      plot.background = ...,
      ...
    )
    

    For each element you customize, you may need to use theme element functions like element_rect(), element_line(), or element_text(). There is also the function element_blank() that can completely remove an element if you do not want it. Again, if you look at the documentation for theme, it will describe which function you need to use for each setting.

    element_rect()   # borders and backgrounds
    element_line()   # lines
    element_text()   # text
    element_blank()  # draw nothing
    
    In [18]:
    # To check documentations for theme customization
    library(ggplot2)
    
    # Create a factor from the 'gear' column in mtcars
    mtcars$gearfactor <- factor(mtcars$gear)
    
    # Create the plot with customized theme
    ggplot(mtcars, aes(x = gearfactor, fill = gearfactor)) + 
      geom_bar() +  
      scale_fill_brewer(palette = "Set3") +
      theme(
        # Customize various elements of the plot
        axis.line = element_line(color = "red", size = 0.5),  # X and Y axis lines
        axis.text.x = element_text(color = "blue", size = 10, angle = 45, hjust = 1),  # X-axis text
        axis.title.y = element_text(face = "italic"),  # Y-axis title
        legend.background = element_rect(fill = "gray90", color = "black", size = 0.5),  # Legend background
        plot.title = element_text(size = 16, hjust = 0.5, face = "bold"),  # Plot title
        plot.background = element_rect(fill = "lightblue"),  # Plot background
        panel.grid.major = element_blank(),  # Remove major gridlines
        panel.grid.minor = element_blank()   # Remove minor gridlines
      )
    

    Example¶

    Let's use the base chart:

    ggplot(mtcars, aes(cyl)) +
      geom_bar() +
      ggtitle("Number of Cylinders")
    

    and do the following:

    • Change the background using plot.background() and the theme element element_rect(). The color refers to the color of the background border line and the fill is the color of the background.
    • Change the plot title using element_text() to make it bold and blue.
    • Change the color of the x and y axis lines, using element_line() and set the color.
    • Remove the axis tick marks using element_blank()
    In [19]:
    library(ggplot2)
    
    # Create the base chart
    base_chart <- ggplot(mtcars, aes(cyl)) +
      geom_bar() +
      ggtitle("Number of Cylinders")
    
    # Customize the theme
    base_chart +
      theme(
        # Change the background
        plot.background = element_rect(fill = "lightgray", color = "black"),
        
        # Change the plot title
        plot.title = element_text(color = "blue", face = "bold"),
        
        # Change the color of the x and y axis lines
        axis.line = element_line(color = "green"),
        
        # Remove the axis tick marks
        axis.ticks = element_blank()
      )
    
    In [20]:
    ggplot(mtcars, aes(cyl)) +
      geom_bar() +
      ggtitle("Number of Cylinders") +
      theme(
        plot.background = element_rect(color = "green", 
                                       fill = "gray"),
        plot.title = element_text(face = "bold",
                                  color = "blue"),
        axis.line = element_line(color = "red"),
        axis.ticks = element_blank()
      )
    

    Question #2 (c):

    Plot a boxplot with "mpg" on the y axis. Change the background to any color, choose one here. Also, remove the x text ("axis.text.x").

    In [21]:
    # Write your code below and press Shift+Enter to execute 
    ggplot(mtcars, aes(y = mpg)) +
         geom_boxplot() +
         labs(y = "Miles per gallon", title = "Boxplot") +
         theme(
             plot.background = element_rect(fill = "skyblue"),
             axis.text.x = element_blank()
         )
    
    Click here for the solution.
    ggplot(mtcars, aes(y = mpg)) +
         geom_boxplot() +
         labs(y = "Miles per gallon", title = "Boxplot") +
         theme(
             plot.background = element_rect(fill = "skyblue"),
             axis.text.x = element_blank()
         )
    

    ggthemes package¶

    Customizing your own theme gives you a lot of freedom, but the process may be tedious. A helpful package that includes more themes and color scales is the ggthemes package.

    To use it, you must first install it and load it because it is not included in the ggplot2 package.

    In [22]:
    install.packages("ggthemes")
    library(ggthemes)
    
    Updating HTML index of packages in '.Library'
    Making 'packages.html' ... done
    

    Next, we will go over some examples but there are lots of theme options, so feel free to explore the documentation.

    Examples¶

    This is a scatter plot that uses the default ggplot() theme and color palette. You can store the base plot in a variable to make it easy to try different themes. In this example, we name it p.

    In [23]:
    p <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
      geom_point(aes(color = factor(cyl))) +
      labs(
        x = "Weight (1000 lbs)", 
        y = "Miles/(US) gallon", 
        color = "Cylinders"
        )
    p
    

    Using the ggthemes package, you can change the plot to follow the “economist” theme and colors by simply adding the theme_economist() and scale_color_economist() functions to the base plot “p”.

    In [24]:
    p + theme_economist() + scale_color_economist()
    
    Error in element_line(linewidth = rel(0.8)): unused argument (linewidth = rel(0.8))
    Traceback:
    
    1. theme_economist()
    2. theme(line = element_line(colour = "black"), rect = element_rect(fill = bgcolors["ebg"], 
     .     colour = NA, linetype = 1), text = element_text(colour = "black"), 
     .     axis.line = element_line(linewidth = rel(0.8)), axis.line.y = element_blank(), 
     .     axis.text = element_text(size = rel(1)), axis.text.x = element_text(vjust = 0, 
     .         margin = margin(t = base_size, unit = "pt")), axis.text.x.top = element_text(vjust = 0, 
     .         margin = margin(b = base_size, unit = "pt")), axis.text.y = element_text(hjust = 0, 
     .         margin = margin(r = base_size, unit = "pt")), axis.ticks = element_line(), 
     .     axis.ticks.y = element_blank(), axis.title = element_text(size = rel(1)), 
     .     axis.title.x = element_text(), axis.title.y = element_text(angle = 90), 
     .     axis.ticks.length = unit(-base_size * 0.5, "points"), legend.background = element_rect(linetype = 0), 
     .     legend.spacing = unit(base_size * 1.5, "points"), legend.key = element_rect(linetype = 0), 
     .     legend.key.size = unit(1.2, "lines"), legend.key.height = NULL, 
     .     legend.key.width = NULL, legend.text = element_text(size = rel(1.25)), 
     .     legend.text.align = NULL, legend.title = element_text(size = rel(1), 
     .         hjust = 0), legend.title.align = NULL, legend.position = "top", 
     .     legend.direction = NULL, legend.justification = "center", 
     .     panel.background = element_rect(linetype = 0), panel.border = element_blank(), 
     .     panel.grid.major = element_line(colour = "white", linewidth = rel(1.75)), 
     .     panel.grid.minor = element_blank(), panel.spacing = unit(0.25, 
     .         "lines"), strip.background = element_rect(fill = bgcolors["ebg"], 
     .         colour = NA, linetype = 0), strip.text = element_text(size = rel(1.25)), 
     .     strip.text.x = element_text(), strip.text.y = element_text(angle = -90), 
     .     plot.background = element_rect(fill = bgcolors["blue-gray"], 
     .         colour = NA), plot.title = element_text(size = rel(1.5), 
     .         hjust = 0, face = "bold"), plot.margin = unit(c(6, 5, 
     .         6, 5) * 2, "points"), complete = TRUE)
    3. find_args(..., complete = NULL, validate = NULL)
    4. mget(args, envir = env)

    Here is another example that uses a clean theme and a color palette that is colorblind safe.

    In [25]:
    p + theme_clean() + 
        scale_color_colorblind()
    

    Question #2 (d):

    Use the same base plot, p. Add a different theme and color scale from "ggthemes" using the documentation.

    In [26]:
    # Write your code below and press Shift+Enter to execute 
    
    p + theme_gdocs() + scale_color_gdocs()
        
    p + theme_igray() + scale_color_canva()
    
    Click here for the solution.
    # Some example solutions
    
    p + theme_gdocs() + scale_color_gdocs()
    
    p + theme_igray() + scale_color_canva()
    

    3. Maps with Leaflet

    Map packages in R¶

    There are a number of packages available for working with maps in R, such as ggmaps, RgoogleMaps, or the built-in “maps” library.   We’re going to focus on the Leaflet library, which allows you to create interactive maps. Leaflet is a powerful library capable of producing complex visuals, like this street map of Times Square. But even though it’s a powerful tool, it’s generally very simple to use.

    Make sure to install it if you haven’t already done so, and then load it using the “library” function.

    Please note that this lab requires 'leaflet' and its dependent 'leaflet.providers' packages. These packages are pre-installed in this lab environment. However, if you are doing this lab locally in the R-Studio desktop, you need to run 'install.packages' command as given below -

    " install.packages('leaflet', dependencies = T) "

    " install.packages('leaflet.providers', dependencies = T) "

    Proceed to load 'leaflet' package using the “library” function as shown below.

    In [31]:
    install.packages("htmltools", repos = "https://cloud.r-project.org/")
    
    Updating HTML index of packages in '.Library'
    Making 'packages.html' ... done
    
    In [1]:
    library(htmltools)
    
    In [2]:
    library(leaflet)
    

    Creating simple maps in r¶

    To begin, we use the “leaflet” function, which returns an object that represents an empty world map.   Next, we call the “addTiles” function to publish a tile layer on the map. This allows us to zoom in and see the countries and cities in detail.   Notice that we’re using the special operator %>%. This is the pipe operator from the magrittr package. Pipe passes the item on its left into the first parameter of the function on its right, and then returns the result. So this code will send the output of “leaflet” to the first parameter of “addTiles”, and this result is returned to the “map” variable.

    In [3]:
    map <- leaflet() %>% addTiles()
    map
    

    Also, you can read %>% as "then" in the code. So in the above code it's like saying first create leaflet object, then add tiles.

    Adding markers¶

    You can also display a specific location with a marker, like we’ve done with Times Square on this map.

    To do so, use the “addMarkers” function, and specify the longitude and latitude of your location.

    In [4]:
    map <- leaflet() %>% addTiles() %>%
           addMarkers(lng = 77.5946, lat = 12.9716)
    map
    

    Adding captions¶

    To add a caption to a specific location, you can use the “popup” argument. So now it’s clear that this marker denotes the location of Times Square.

    In [5]:
    map <- leaflet() %>% addTiles() %>%
           addMarkers(lng = -71.1395821, lat =42.3470294 )
    map
    
    In [6]:
    map <- leaflet() %>% addTiles() %>%
           addMarkers(lng = -73.9851, lat = 42.3470294)
    map
    
    In [7]:
    map <- leaflet() %>% addTiles() %>% 
           addMarkers(lng = -73.9851, lat = 40.7589, popup = 'Times Square')
    map
    

    Changing the tile¶

    You can create maps with different styles, like the watercolor style you see here. We use the addProviderTiles() function with the argument “Stamen.Watercolor”. There are a variety of different styles to choose from, so there are a lot of opportunities to customize your map.

    In [8]:
    map <- leaflet() %>% addProviderTiles("Stamen.Watercolor") %>% 
           addMarkers(lng = 2.2945, lat = 48.8584, popup = "Eiffel Tower")
    map
    

    Creating maps from a data frame¶

    Let’s now use a data set in order to add markers to a map.

    We use the built-in “quakes” dataset, which provides the locations of 1000 earthquakes near Fiji since 1964. For each earthquake, the dataset holds the longitude, latitude, depth, magnitude, and number of stations.

    In [11]:
    head(quakes)
    
    A data.frame: 6 × 5
    latlongdepthmagstations
    <dbl><dbl><int><dbl><int>
    1-20.42181.625624.841
    2-20.62181.036504.215
    3-26.00184.10 425.443
    4-17.97181.666264.119
    5-20.42181.966494.011
    6-19.68184.311954.012

    Adding Multiple Markers¶

    Let's add multiple markers onto a map. But this time we’ll make sure to provide the longitude and latitude of all the points that we want to plot. You can see that we have created the markers, but now the map is starting to look a little too cluttered.

    In [9]:
    map <- leaflet(quakes) %>% addTiles() %>% 
           addCircleMarkers(lng = quakes$long, lat = quakes$lat)
    map
    

    Clustering markers¶

    We can improve the clarity by grouping the markers into clusters. The “clusterOptions” parameter will group the markers by region, and display the number of markers in each region.

    In [10]:
    map <- leaflet(quakes) %>% addTiles() %>% 
           addCircleMarkers(clusterOptions = markerClusterOptions())
    map
    
    Assuming "long" and "lat" are longitude and latitude, respectively
    

    Adding circles¶

    Another option is to display circles for each point. These circles can be rescaled with the whole map when you zoom in or out. Notice that we’re using the addCircles() function, rather than the “addCircleMarkers” function from earlier.

    In [11]:
    map <- leaflet(quakes) %>% addTiles() %>% 
           addCircles(lng = quakes$long, lat = quakes$lat)
    map
    

    Adding rectangles¶

    If you want to highlight an area of interest, you can use the addRectangles() function. The arguments are the coordinates of two points, which serve as the rectangle’s delimiters.

    In [12]:
    map <- leaflet(quakes) %>% addTiles() %>% 
           addMarkers(lng = 86.92, lat = 27.99, popup = "Mount Everest") %>%
           addRectangles(86.9, 27.95, 87, 28.05)
    map
    

    Adding other features¶

    We mentioned at the beginning that Leaflet is a powerful library that provides a lot of functionality. We’ve only scratched the surface, but Leaflet allows you to add different colors, legends, lines, and shapes. So once you get used to the interface, you’ll be able to use Leaflet to its full potential.

    Here is the leaflet documentation for more information.

    Question #3:

    Using the "quakes" dataset, add circles and give them color to visualize magnitude (mag). Also, add a legend for the magnitudes. Try following the first example in the legend section in the documentation.

    Hint: define a palette first like

    pal <- colorNumeric(
          palette = "Reds",
          domain = quakes$mag)
    
    In [13]:
    # Write your code below and press Shift+Enter to execute 
    # define numeric color palette
    pal <- colorNumeric(
      palette = "Reds",
      domain = quakes$mag)
      
    # add circles and legend to map
    map <- leaflet(quakes) %>% addTiles() %>% 
      addCircles(lng = quakes$long, 
                 lat = quakes$lat, 
                 color = ~pal(mag)) %>%  # color the circle of each magnitude using the palette defined
      addLegend("bottomright",           # add legend to the bottom right
                pal = pal,               # use the defined color palette
                values = ~mag,           # use the mag variable
                title = "Magnitude")
    
    # show map
    map
    
    Click here for the solution.
    # define numeric color palette
    pal <- colorNumeric(
      palette = "Reds",
      domain = quakes$mag)
    
    # add circles and legend to map
    map <- leaflet(quakes) %>% addTiles() %>% 
      addCircles(lng = quakes$long, 
                 lat = quakes$lat, 
                 color = ~pal(mag)) %>%  # color the circle of each magnitude using the palette defined
      addLegend("bottomright",           # add legend to the bottom right
                pal = pal,               # use the defined color palette
                values = ~mag,           # use the mag variable
                title = "Magnitude")
    
    # show map
    map
    

    About the Author:¶

    Hi! It's Yiwen Li and Tiffany Zhu, the authors of this notebook. We hope you found R easy to learn! There's lots more to learn about R but you're well on your way. Feel free to connect with us if you have any questions.


    Copyright © 2021 IBM Corporation. All rights reserved.